package fmppc.manager;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 类描述:  驼峰与下划线互转
 *
 * @author 王雷
 * @version 1.0.0
 * @date 2022/12/9 0009 下午 8:28
 */
public class UnderlineToCamelUtils {

    /**
     * 属性描述：下划线转驼峰表达式
     * @date : 2022/12/9 0009 下午 8:30
     */
    private static final Pattern UNDER_TO_CAMEL_PATTERN = Pattern.compile("([A-Za-z\\d]+)(_)?");

    /**
     * 下划线转驼峰法
     *
     * @param line       源字符串
     * @param smallCamel 大小驼峰,是否为小驼峰
     * @return 转换后的字符串
     */
    public static String underlineToCamel(String line, boolean smallCamel) {
        if (line == null || "".equals(line)) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        Matcher matcher = UNDER_TO_CAMEL_PATTERN.matcher(line);
        while (matcher.find()) {
            String word = matcher.group();
            sb.append(smallCamel && matcher.start() == 0 ? Character.toLowerCase(word.charAt(0)) : Character.toUpperCase(word.charAt(0)));
            int index = word.lastIndexOf('_');
            if (index > 0) {
                sb.append(word.substring(1, index).toLowerCase());
            } else {
                sb.append(word.substring(1).toLowerCase());
            }
        }
        return sb.toString();
    }

    /**
     * 属性描述：驼峰转下划线表达式
     * @date : 2022/12/9 0009 下午 8:30
     */
    private static final Pattern CAMEL_TO_UNDER_PATTERN = Pattern.compile("[A-Z]([a-z\\d]+)?");

    /**
     * 驼峰法转下划线
     *
     * @param line 源字符串
     * @return 转换后的字符串
     */
    public static String camelToUnderline(String line) {
        if (line == null || "".equals(line)) {
            return "";
        }
        line = String.valueOf(line.charAt(0)).toUpperCase().concat(line.substring(1));
        StringBuilder sb = new StringBuilder();

        Matcher matcher = CAMEL_TO_UNDER_PATTERN.matcher(line);
        while (matcher.find()) {
            String word = matcher.group();
            sb.append(word.toUpperCase());
            sb.append(matcher.end() == line.length() ? "" : "_");
        }
        return sb.toString();
    }
}
